package com.pn.warehouse.controller;

import com.pn.warehouse.dto.AssignRoleDto;
import com.pn.warehouse.entity.CurrentUser;
import com.pn.warehouse.entity.Result;
import com.pn.warehouse.entity.Role;
import com.pn.warehouse.entity.User;
import com.pn.warehouse.page.Page;
import com.pn.warehouse.service.RoleService;
import com.pn.warehouse.service.UserService;
import com.pn.warehouse.utils.DigestUtil;
import com.pn.warehouse.utils.TokenUtils;
import com.pn.warehouse.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private RoleService roleService;

    /**
     * 分页查询用户信息
     * @param page ：分页的信息
     * @param user ：条件查询的用户
     */
    @RequestMapping("/user-list")
    public Result userList(Page page, User user){
        //执行业务并返回
        page = userService.queryByUserPage(page, user);
        return Result.ok(page);
    }

    /**
     * 添加用户
     * @RequestBody ：接受并封装前端传递的json数据的用户信息
     */
    @RequestMapping("/addUser")
    public Result addUser(@RequestBody User user, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        System.out.println(user.toString());

        //1、判断用户是否已经存在
        User u = userService.fingUserByCode(user.getUserCode());
        if (u != null){
            return Result.err(Result.CODE_ERR_BUSINESS, "账号已经存在！");
        }

        //2、从token中拿到当前登陆用户的id，并赋值给添加用户的创建人
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        int userId = currentUser.getUserId();
        user.setCreateBy(userId);

        //3、对密码进行md5加密
        user.setUserPwd(DigestUtil.hmacSign(user.getUserPwd()));

        //4、执行添加操作
        int i = userService.addUser(user);
        if (i > 0){
            return Result.ok("用户添加成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "用户添加失败！");
    }

    /**
     * 启用或者禁用用户的状态
     */
    @RequestMapping("/updateState")
    public Result updateUserState(@RequestBody User user){
        //1、修改用户的状态并返回(前端传过来的用户状态是修改过的)
        int i = userService.setUserState(user);
        if (i > 0){
            return Result.ok("启用或者禁用用户成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "启用或者禁用用户成功失败！");
    }

    /**
     * 查询用户已分配的角色，并回显给前端
     */
    @RequestMapping("/user-role-list/{userId}")
    public Result userRoleList(@PathVariable Integer userId){
        //1、执行业务并返回
        List<Role> roleList = roleService.queryUserRoleByUid(userId);
        return Result.ok(roleList);
    }

    /**
     * 给用户分配角色
     * 1、先根据用户id在用户角色关系表中删除之前分配的角色
     * 2、再根据角色名字查询到角色的id
     * 3、把新分配的角色添加到用户角色关系表中
     */
    @RequestMapping("/assignRole")
    public Result assignRole(@RequestBody AssignRoleDto assignRoleDto){
        //1、执行业务并返回
        userService.assignRole(assignRoleDto);
        return Result.ok("分配角色成功！");
    }

    /**
     * 根据用户单个id删除用户
     */
    @RequestMapping("/deleteUser/{userId}")
    public Result removeUserById(@PathVariable Integer userId){
        //1、执行业务并返回
        Result result = userService.deleteUserById(Arrays.asList(userId));
        return result;
    }

    /**
     * 批量删除用户
     */
    @RequestMapping("/deleteUserList")
    public Result removeUserByIds(@RequestBody List<Integer> userIdsList){
        //1、执行业务并返回
        Result result = userService.deleteUserById(userIdsList);
        return result;
    }

    /**
     * 根据id修改用户昵称
     */
    @RequestMapping("/updateUser")
    public Result updateUser(@RequestBody User user, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        //1、从token中拿到当前用户的id
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        int userId = currentUser.getUserId();
        //2、设置修改的用户id
        user.setUpdateBy(userId);
        //3、执行业务并返回
        Result result = userService.updateUserNameById(user);
        return result;
    }

    /**
     * 根据用户id修改密码
     * 重置密码为123455
     */
    @RequestMapping("/updatePwd/{userId}")
    public Result resetPwd(@PathVariable Integer userId){
        //1、执行业务并返回
        Result result = userService.updatePwdById(userId);
        return result;
    }

}
